﻿using System;
using System.Web;
using Dexter.Dependency;
using Dexter.Web;

namespace Dexter.Host.Web.Mvc {
	public class MvcApplication : HttpApplication {
		static readonly IDexterApplication dexterApplication;

		static MvcApplication ( ) {
			DexterContainer.StartUp ( );
			dexterApplication = DexterContainer.Resolve <IDexterApplication> ( );
		}

		public override void Init ( ) {
			base.Init ( );
			dexterApplication.Init ( this );
		}

		protected void Application_Start ( object sender , EventArgs e ) {
			dexterApplication.ApplicationStart ( );
		}

		protected void Application_BeginRequest ( object sender , EventArgs e ) {
			var app = ( HttpApplication ) sender;
			HttpContext context = app.Context;

			// Attempt to peform first request initialization
			FirstRequestInitialization.Initialize ( context );
		}

		protected void Application_AuthenticateRequest ( object sender , EventArgs e ) {
			dexterApplication.AuthenticateRequest ( );
		}

		protected void Application_Error ( object sender , EventArgs e ) {
			dexterApplication.ApplicationError ( );
		}

		protected void Application_End ( object sender , EventArgs e ) {
			dexterApplication.ApplicationEnd ( );
		}
	}

	internal class FirstRequestInitialization {
		static bool initializedAlready;
		static readonly object @lock = new object ( );

		// Initialize only on the first request
		public static void Initialize ( HttpContext context ) {
			if ( initializedAlready ) {
				return;
			}

			lock ( @lock ) {
				if ( initializedAlready ) {
					return;
				}
				InizializeWithContext ( );
				initializedAlready = true;
			}
		}

		static void InizializeWithContext ( ) {}
	}
}